<?php
namespace App\Models;

class ShopGoodsStock extends BaseModel
{
    protected $table = 'shop_goods_stock';

    // 入库
    public function addGoodsStock($goodsInfo, $num)
    {
        $data['shop_id'] = $goodsInfo['shop_id'];
        $data['admin_id'] = $goodsInfo['admin_id'];
        $data['goods_id'] = $goodsInfo['goods_id'];
        $data['shop_goods_id'] = $goodsInfo['id'];
        $data['goods_name'] = $goodsInfo['goods_name'];
        $data['before_store'] = $goodsInfo['goods_num'];
        $data['num'] = $num;

        if($data['num'] <1) {
            $this->error = '入库数量不能小于1';
            return false;
        }

        $this->_start();
        try{
            // 保存入库日志
            $res = $this->_save($data);
            if(!$res) {
                $this->_rollBack();
                $this->error = '入库失败';
                return false;
            }

            // 更新库存
            (new ShopGoods())->_inc(['id'=>$goodsInfo['id']],'goods_num', $num);

            $this->_commit();
            return true;
        }catch(\Exception $e) {
            $this->_rollBack();
            $this->error = '入库失败';
            return false;
        }
    }

}